package com.example.backblog.controller.blog;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.backblog.apijson.DemoParser;
import com.example.backblog.dao.BlogMapper;
import com.example.backblog.dao.BlogTagMapper;
import com.example.backblog.dto.blog.BlogDto;
import com.example.backblog.entity.blog.Blog;
import com.example.backblog.entity.blog.BlogTag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogMapper blogMapper;
    @Autowired
    private BlogTagMapper blogTagMapper;
    @PostMapping("/addOneBlog")
    public JSONObject addOneBlog(@RequestBody BlogDto blogDto){
        Blog blog = new Blog();
        BeanUtils.copyProperties(blogDto,blog);
        // 设置修改时间
        blog.setModifyTime(new Date());
        if (blogDto.getId() == null) {
            blogMapper.insert(blog);

        }else{
            blogMapper.updateById(blog);
            QueryWrapper<BlogTag> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("blogId",blog.getId());
            blogTagMapper.delete(queryWrapper);
        }
        if (blogDto.getTags() != null) {
            blogDto.getTags().stream().forEach(tagId->{
                BlogTag blogTag = new BlogTag();
                blogTag.setBlogId(blog.getId());
                blogTag.setTagId(tagId);
                blogTagMapper.insert(blogTag);
            });
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("obj",blog);

        return DemoParser.extendSuccessResult(jsonObject);
    }

    @GetMapping("/tags")
    public JSONObject tags(Long blogId){
        QueryWrapper<BlogTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("blogId",blogId);
        List<BlogTag> blogTags = blogTagMapper.selectList(queryWrapper);
        List<Long> collect = blogTags.stream().map(blogTag -> blogTag.getTagId()).collect(Collectors.toList());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tags",collect);
        return DemoParser.extendSuccessResult(jsonObject);
    }

    @GetMapping("/top")
    @Transactional
    public JSONObject updateTop(Long blogId){
        blogMapper.resetBlogTop();
        Blog blog = blogMapper.selectById(blogId);
        blog.setTop(true);
        blogMapper.updateById(blog);
        return DemoParser.newSuccessResult();
    }

    @DeleteMapping("/delete/one")
    public JSONObject deleteBlog(long id){
        Blog blog = blogMapper.selectById(id);
        blog.setDeleteFlag(true);
        blogMapper.updateById(blog);
        return DemoParser.newSuccessResult();
    }


}
